package com.zh.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotRoleException;
import com.zh.common.BaseResponse;
import com.zh.common.ErrorCode;
import com.zh.common.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import javax.servlet.http.HttpServletResponse;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(NotLoginException.class)
    public BaseResponse<?> exceptionHandler(NotLoginException e, HttpServletResponse response) {
        log.error("未登录", e);
        response.setStatus(401);
        return ResultUtils.error(ErrorCode.NOT_LOGIN_ERROR, "未登录");
    }

    @ExceptionHandler(NotRoleException.class)
    public BaseResponse<?> exceptionHandler(NotRoleException e, HttpServletResponse response) {
        log.error("无权限", e);
        response.setStatus(403);
        return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "无权限");
    }

    @ExceptionHandler(BusinessException.class)
    public BaseResponse<?> businessExceptionHandler(BusinessException e) {
        log.error("系统错误 BusinessException", e);
        return ResultUtils.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(RuntimeException.class)
    public BaseResponse<?> runtimeExceptionHandler(RuntimeException e) {
        log.error("RuntimeException", e);
        return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "系统错误");
    }

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public BaseResponse<?> maxUploadSizeExceededExceptionHandler(MaxUploadSizeExceededException e) {
        log.error("MaxUploadSizeExceededException", e);
        return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "超过文件大小限制");
    }

}
